﻿using Microsoft.AspNetCore.Mvc;
using PlatformNetCore.Common;
using PlatformNetCore.Common.Helper;
using PlatformNetCore.Common.Utility;
using PlatformNetCore.Entity;
using PlatformNetCore.IService;
using PlatformNetCore.Web.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;

namespace PlatformNetCore.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class SubscribeController : BaseController
    {
        private readonly ISubscribeService subscribeService;
        private readonly IPathProvider pathProvider;
        public SubscribeController(ISubscribeService _subscribeService, IPathProvider _pathProvider)
        {
            subscribeService = _subscribeService;
            pathProvider = _pathProvider;
        }

        #region 留言管理
        [RoleAuthorize("SubscribeList")]
        public IActionResult SubscribeList(string search = "", int pageindex = 1, int pagesize = 15)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    Expression<Func<Subscribe, bool>> predicate = s => s.IsDel == 0;
                    if (!string.IsNullOrWhiteSpace(search))
                    {
                        predicate = predicate.And(k => k.Title.Contains(search));
                    }
                    return Json(subscribeService.GetSubscribePagedList(pageindex, pagesize, predicate));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Content(CommonConst.SystemErrorMessage);
            }
            return View();
        }
        /// <summary>
        /// 发放列表导出
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="status"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        [RoleAuthorize("SubscribeExport")]
        public IActionResult SubscribeExport(string search = "")
        {
            try
            {
                Expression<Func<Subscribe, bool>> predicate = s => s.IsDel == 0;
                if (!string.IsNullOrWhiteSpace(search))
                {
                    predicate = predicate.And(k => k.Title.Contains(search));
                }
                var response = subscribeService.GetSubscribePagedList(1, 65535, predicate);
                if (response.data != null)
                {
                    var list = response.data;
                    int n = 0;
                    DataTable dt = list.Select(a => new
                    {
                        i = ++n,
                        a.Title,
                        a.Person,
                        a.Phone,
                        a.Email,
                        a.Content,
                        AddDate = a.AddDate.HasValue ? a.AddDate.Value.ToString("yyyy-MM-dd") : "--"
                    }).ToList().ToDataTable();

                    string cname = "序号,标题,联系人,联系电话,联系邮箱,内容,留言时间";
                    string[] cnames = cname.Split(',');
                    List<string> tbColumnName = cnames.ToList();
                    string basePath = AppSettings.OutputExcelTemplatePath;
                    string downLoadPath = string.Empty;
                    if (ExcelHelper.GetInterimOutPutFilePath(pathProvider, ref basePath,ref downLoadPath, "留言列表导出"))
                    {
                        string filePath = pathProvider.MapPath(basePath);
                        if (ExcelHelper.Output(dt, filePath, true, tbColumnName, "留言列表"))
                        {
                            return Json(new { msg = "导出成功", url = downLoadPath, success = true });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            return Json(new { msg = "导出失败，请重试", success = false });
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [RoleAuthorize("SubscribeAdd")]
        public IActionResult SubscribeAdd()
        {
            try
            {
                Subscribe model = new Subscribe();
                return View(model);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Content(CommonConst.SystemErrorMessage);
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [RoleAuthorize("SubscribeAdd")]
        public IActionResult SubscribeAdd(Subscribe model)
        {
            try
            {
                model.AddBy = CurrentUser.Login;
                return Json(subscribeService.AddSubscribe(model));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Json(new { success = false, msg = CommonConst.SystemErrorMessage });
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pageindex"></param>
        /// <returns></returns>
        [HttpPost]
        [RoleAuthorize("SubscribeDel")]
        public IActionResult SubscribeDel(string id)
        {
            try
            {
                List<string> ids = new List<string>() { id };
                return Json(subscribeService.UpdateSubscribeState(ids, CurrentUser.Login, DataStatus.Deleted));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Json(new { success = false, msg = CommonConst.SystemErrorMessage });
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [RoleAuthorize("SubscribeEdit")]
        public IActionResult SubscribeEdit(string id)
        {
            try
            {
                ResultResponse<Subscribe> result = subscribeService.GetSubscribe(id);
                return View(result.data);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Content(CommonConst.SystemErrorMessage);
            }
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [RoleAuthorize("SubscribeEdit")]
        public IActionResult SubscribeEdit(Subscribe model)
        {
            try
            {
                model.UpdateBy = CurrentUser.Login;
                return Json(subscribeService.UpdateSubscribe(model));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return Json(new { success = false, msg = CommonConst.SystemErrorMessage });
            }
        }
        #endregion

    }
}